<?php
/**
 * @abstract 获取微信acces_token，获取微信SignPackage
 * 微信acces_token 全局使用，有效期7200秒，失效后调用时刷新，并重新保存数据
 * 微信SignPackage 全局使用，有效期7200秒，失效后调用刷新，供微信分享。分页jssdk使用
 * w_token表，id=1,存储微信acces_token的值，id=2,存储微信ticket。
 * @author ran
 * date 2016-04-25
 */
namespace services\models\wap;

use Yii;

/**
 * This is the model class for table "iliketry.w_token".
 *
 * @property integer $id
 * @property string $token
 * @property integer $expires
 */
class WeiXinToken extends \common\models\wap\WeiXinToken
{ 
    
    private $appId;
    private $appSecret;
    
    public function  init(){
        $this->appId = Yii::$app->params['wxpay']['appid'];
        $this->appSecret = Yii::$app->params['wxpay']['appsecret'];        
    }
    
    
    /**
     *获取w_token信息
     */
    public  function getTokenInfo() 
    {
        $token_info = self::findOne(['id'=>1]);
        if(!$token_info) {
            return null;
        }
        
        //检测当前token是否失效，失效后重新拉取
        if ((empty($token_info->token) || $token_info->expires + 7200 < time()))
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $token_info->token = $access_token;
                $token_info->expires = time();
                $token_info->save();
            }
        } else {
            $access_token = $token_info->token;
        }
        
        return $access_token;
    }
    
    
    
    /**
     * 获取SignPackage
     */
    public function getSignPackage() {
        
        $jsapiTicket = $this->getJsApiTicket();
        
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
    
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    
        $signature = sha1($string);
    
        $signPackage = [
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        ];
    
        return $signPackage;
    }
    
    
    /**
     * 获取随机字符串
     * @param number $length
     */
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    /**
     * 获取ticket
     */
    private function getJsApiTicket()
    {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $ticket_info = self::findOne(['id'=>2]);
        if(!$ticket_info) {
            return null;
        }
        
        if ($ticket_info->expires+7000 < time())
        {
            $acces_token = $this->getTokenInfo();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$acces_token;
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $ticket_info->token = $ticket;
                $ticket_info->expires = time();
                $ticket_info->save();
            }
        } else {
            
            $ticket = $ticket_info->token;
        }
    
        return $ticket;
    }
    
    
    /**
     * http get请求
     * @param unknown $url
     */
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
    
        $res = curl_exec($curl);
        curl_close($curl);
    
        return $res;
    }
    
}
